package com.olive.authentication;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

	private UserDetailsService userDetailsService;

	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	//重写两个方法--authenticate()和supports()
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		//认证之前
		SmsCodeAuthenticationToken token = (SmsCodeAuthenticationToken) authentication;
		//认证之前Principal存放的是手机号
		UserDetails userDetails = userDetailsService.loadUserByUsername((String) token.getPrincipal());
		if (userDetails==null){
			throw new InternalAuthenticationServiceException("无法根据手机号获取用户信息");
		}
		//认证之后,此时将获取的userDetails存放进Principal
		SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());
		smsCodeAuthenticationToken.setDetails(token.getDetails());
		return smsCodeAuthenticationToken;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}
}

